package keenabc

import (
	"fmt"
	"database/sql"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"strings"
	"os"
)

type Table struct {
	TableName       	string
}

func GetDB() []Table {

	var connstr string
	connstr = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8",
		beego.AppConfig.String("user"),
		beego.AppConfig.String("password"),
		beego.AppConfig.String("host"),
		beego.AppConfig.String("port"),
		beego.AppConfig.String("db"))

	/*db, err :=*/ sql.Open("mysql", connstr)
/*
	var strsql string*/

	o := orm.NewOrm()

	var users []Table
	o.Raw("SELECT table_name FROM information_schema.TABLES WHERE table_schema = 'dockingwork'").QueryRows(&users)

	return users
}

func NewModel(tableName string) {
	path, _ := os.Getwd()
	//fmt.Println(path)
	FileName := NameChange(tableName)


	o := orm.NewOrm()

	var users []TableStruct
	o.Raw("select column_name, data_type from information_schema.COLUMNS where TABLE_SCHEMA = 'dockingwork' and TABLE_NAME = ?;", tableName).QueryRows(&users)


	//Create Model
	model, _ := os.OpenFile(path+"/models/"+ FileName + ".go" , os.O_CREATE|os.O_RDWR, 0766)

	var modelstr string

	for i := 0; i < len(users); i++ {
		var temp string
		kv := strings.SplitN(users[i].DataType, "(", 2)
		switch kv[0] {
		case "varchar" :
			temp = "string"
		case "int" :
			temp = "int"
		}
		modelstr += NameChange(users[i].ColumnName) + " " + temp + " `orm:\"column("+ users[i].ColumnName +");\"`\n"
	}

	modelTpl = strings.Replace(modelTpl, "{{StructName}}", FileName, -1)
	modelTpl = strings.Replace(modelTpl, "{{StructContent}}", modelstr, -1)
	modelTpl = strings.Replace(modelTpl, "{{TableName}}", tableName, -1)
	modelTpl = strings.Replace(modelTpl, "{{structname}}", strings.ToLower(FileName), -1)

	model.WriteString(modelTpl)

	GoFmt(path+"/models/"+ FileName + ".go")
}